import time

from mysql_conf import mysel_conf

conn = mysel_conf.pool()
cursor = conn.cursor()
import requests
import io, math, random, string,oss2
from PIL import Image
import config,os,time,pymongo
from utils import get_mongo_collection
webp_mysql_updated = get_mongo_collection('webp_mysql_updated')
'''

    要处理的文章

'''

def get_content_ext_id_for_img():
    last_id=0
    # 得到mongo的最大id
    last_mongo=webp_mysql_updated.find().sort('contents_is', pymongo.DESCENDING )
    for i in last_mongo:
        last_id=i['contents_id']

    sql = "SELECT *  FROM contents_ext    where contents_id in (select id FROM contents where media_type=1 and status=0 order by id desc )  and contents_id > %s GROUP BY contents_id order by id asc "
    cursor.execute(sql,(last_id,))
    res = cursor.fetchall()

    return res
'''

    width 大于1000px -> 1000px

'''
def image_width_mobile(width):
    if width <= 1000:
        return 1
    elif width > 1000:
        return 1000 / width


'''
    def 等比例压缩
    image  图片资源
'''


def image_change_width(image):
    pre = image_width_mobile(image.size[0])
    image.thumbnail((math.ceil(image.size[0] * pre), math.ceil(image.size[1] * pre)))
    return image

'''
    修改图片格式
'''
def image_change_ext(img):
    file_name =set_file_name()
    try:
        img.save('./img/'+file_name+'.webp', "webp")
        return put_object_from_file('./img/'+file_name+'.webp','ext/'+file_name+'.webp')
    except Exception as e:
        print(e)
        img.save('./img/'+file_name+'.jpg', 'JPEG')
        return put_object_from_file('./img/'+file_name+'.jpg','ext/'+file_name+'.jpg')


def set_file_name():
    file_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + '_' + ''.join(
        random.sample(string.ascii_letters + string.digits, 8))
    return file_name



def put_object_from_file(file, file_name):
    auth = oss2.Auth(config.OSS_ACCESS_KEY_ID, config.OSS_ACCESS_KEY_SECRET)
    endpoint = config.OSS_ORIGINAL_URL  # 假设你的Bucket处于杭州区域
    bucket = oss2.Bucket(auth, endpoint, config.OSS_BUCKET , is_cname=True, enable_crc=False)
    bucket.put_object_from_file(file_name, file)
    os.remove(file)
    return file_name
'''
    处理单张图片
'''
def img_webp(pic_link):
    try:
        file = io.BytesIO()
        file.write(requests.get(pic_link).content)
        im = Image.open(file)
        img_link=image_change_ext(im)
        return img_link
    except:
        return ''


def ext_mysql_update_webp(id,link,contents_id):
    sql="UPDATE contents_ext SET webp_link=%s WHERE id=%s"
    cursor.execute(sql,(link,id,))
    sql_contents = "UPDATE contents SET status=0 WHERE id=%s "
    cursor.execute(sql_contents, (contents_id,))
    conn.commit()




def ext_mysql_web_insert(contents_id):
    sql = "SELECT count(*) as num FROM contents_ext where contents_id  = %s"
    cursor.execute(sql,(contents_id))
    res = cursor.fetchone()

    num=res['num']
    if num==6:
        sql_contents = "UPDATE contents SET status=0 WHERE id=%s "
        cursor.execute(sql_contents, (contents_id,))
        conn.commit()
        webp_mysql_updated.insert({'contents_id': contents_id, 'time': int(time.time())})
        return False
    elif num==2 or num==5 or num==8:
        sql = "SELECT * FROM contents_ext    where contents_id  = %s order by contents_sort asc  limit 2 "
        cursor.execute(sql, (contents_id))
        res = cursor.fetchmany(2)
        for i in res:
            if i['webp_link'] !='':
                break
            web_link=img_webp(i['bigpic_link'])
            ext_mysql_update_webp(i['id'],web_link,contents_id)

    else:
        sql = "SELECT * FROM contents_ext  where contents_id = %s order by contents_sort asc limit 1"
        cursor.execute(sql, (contents_id))
        res = cursor.fetchmany(1)
        for i in res:
            if i['webp_link'] !='':
                break
            web_link = img_webp(i['bigpic_link'])
            ext_mysql_update_webp(i['id'], web_link,contents_id)
    webp_mysql_updated.insert({'contents_id': contents_id, 'time': int(time.time())})
def main():
    for c_id in get_content_ext_id_for_img():
        ext_mysql_web_insert(c_id['contents_id'])
if __name__ == '__main__':
    main()